<script setup lang="tsx">
import { ref } from 'vue';
import { $t } from '@/locales';
import { feature, getAPI } from '@/axios-utils';
import { fetchTableQuery, useNetoTable, useTableOperate, useTableScroll } from '@/hooks/common/neto-table';
import { queryDone } from '@/utils/api';
import { UserApi } from '@/api-services/apis/user-api';
import OperateModal from './modules/operate-modal.vue';
import Search from './modules/search.vue';
import { ApiSysUserLoginRuleOut, ApiSysUserLoginRuleQuery } from '@/api-services';
import { SysuserloginruleApi } from '@/api-services/apis/sysuserloginrule-api';
import { ElTag, ElSwitch, ElButton, ElPopconfirm } from 'element-plus';
import Popconfirm from 'element-plus/es/components/popconfirm';
//import Button from 'element-plus/es/components/button';
//import Popconfirm from 'element-plus/es/components/popconfirm';
//import Switch from 'element-plus/es/components/switch';

const { tableWrapperRef, scrollConfig } = useTableScroll();


// 定义 apiFunc 为一个函数，接受参数并返回 Promise
const apiFunc = (params: ApiSysUserLoginRuleQuery) =>
  fetchTableQuery<ApiSysUserLoginRuleQuery, ApiSysUserLoginRuleOut>(params, (internalParams: ApiSysUserLoginRuleQuery) =>
    getAPI(SysuserloginruleApi).getList(internalParams)
  );

const loadingStates = ref<Record<string, boolean>>({});

const {
  columns,
  columnChecks,
  data,
  tableSize,
  loading,
  getData,
  getDataByPage,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useNetoTable({
  apiFn: apiFunc,
  // apiFn:fetchTableQuery(getAPI(ApiuserserviceApi).getPagedList),
  // apiFn: fetchTableQuery(getAPI(ApiuserserviceApi).getPagedList.bind(getAPI(ApiuserserviceApi))),
  apiParams: {
    pageIndex: 1,
    pageSize: 10,
    isEnable: undefined,
    loginRuleType: undefined,
    startDate: undefined,
    endDate: undefined,
    keyWords: undefined
  },
  size: 'small',
  columns: () => [

    { type: 'selection', width: 48 },
    {
      prop: 'id',
      //dataIndex: 'id',
      label: 'id',
      minWidth: 120
    },
    {
      prop: 'creationTime',
      //dataIndex: 'creationTime',
      label: $t('common.creationTime'),
      minWidth: 170
    },
    {
      prop: 'name',
      //dataIndex: 'name',
      label: $t('page.manage.userLoginRule.name'),
      align: 'center',
      minWidth: 100
    },
    {
      //登录规则类别
      prop: 'loginRuleType',
      //dataIndex: 'loginRuleType',
      label: $t('page.manage.common.loginRuleType'),
      align: 'center',
      minWidth: 100,
      formatter: record => {
        switch (record.loginRuleType) {
          case 1:
            return <ElTag type="primary" >{$t('page.manage.common.loginRuleTypeEnum.pwd')}</ElTag>;
          case 2:
            return <ElTag type="success" >IP</ElTag>;
          default:
            return '';
        }
      }
    },

    {
      //允许失败次数
      prop: 'maxFailCount',
      //dataIndex: 'maxFailCount',
      label: $t('page.manage.userLoginRule.maxFailCount'),
      align: 'center',
      minWidth: 100
    },
    {
      //锁定时长
      prop: 'lockMinutes',
      //dataIndex: 'lockMinutes',
      label: $t('page.manage.userLoginRule.lockMinutes'),
      align: 'center',
      minWidth: 100
    },
    // 是否启用
    {
      prop: 'isEnable',
      //dataIndex: 'isEnable',
      label: $t('page.manage.common.isEnable'),
      align: 'center',
      minWidth: 100,
      formatter: record => {
        if (record.isEnable === null) {
          return '';
        }
        const handleSwitchChange = async (checked: boolean | string | number) => {

          // 提交请求
          loadingStates.value = {
            ...loadingStates.value,
            [record.id!]: true
          };
          const [err, res] = await feature(getAPI(SysuserloginruleApi).setIsEnable(record.id!, Boolean(checked)));
          loadingStates.value = {
            ...loadingStates.value,
            [record.id!]: false
          };
          queryDone(err, async () => {
            if (res?.data.data) {
              record.isEnable = Boolean(checked);
            } else {
              window.$message?.error($t('common.failed'));
            }
          });
        };
        return (
          <ElSwitch
            modelValue={record.isEnable}
            onChange={handleSwitchChange}
            loading={loadingStates.value[record.id!] || false}
          ></ElSwitch>
        );
      }
    },
    {
      //备注
      prop: 'remark',
      //dataIndex: 'remark',
      label: $t('page.manage.common.remark'),
      align: 'center',
      minWidth: 200
    },

    {
      prop: 'index',
      label: $t('common.operate'),
      align: 'center',
      fixed: 'right',
      minWidth: 230,
      formatter: record => (
        <div class="flex-center gap-8px" >
          <ElButton type="primary" plain size="small" onClick={() => edit(record.id!)
          }>
            {$t('common.edit')}
          </ElButton>
          <ElPopconfirm onConfirm={() => handleDelete(record.id!)} title={$t('common.confirmDelete')} >
            {{
              reference: () => (
                <ElButton type="danger" plain size="small">
                  {$t('common.delete')}
                </ElButton>
              )
            }}
          </ElPopconfirm>
        </div>
      )
    }
  ]
});

const {
  isVisible,
  operateType,
  editingData,
  editingId,
  handleAdd,
  handleEdit,
  getEditData,
  checkedRowKeys,
  onBatchDeleted,
  onDeleted

} = useTableOperate(data, getData);
const edit = (id: number) => {
  // console.log(id);
  handleEdit(id);
};
const isVisibleRole = ref(false);
const handleDelete = async (id: number) => {
  const ids = [id];

  // 提交请求
  const [err, res] = await feature(getAPI(UserApi).batchDelete(ids));

  queryDone(err, async () => {
    if (res?.data.data) {
      onDeleted();
    } else {
      window.$message?.error($t('common.failed'));
    }
  });
};
const handleBatchDeleted = async () => {
  const ids = checkedRowKeys.value?.map(it => Number(it));

  // 提交请求
  const [err, res] = await feature(getAPI(UserApi).batchDelete(ids));

  queryDone(err, async () => {
    if (res?.data.data) {
      onBatchDeleted();
    } else {
      window.$message?.error($t('common.failed'));
    }
  });
};
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <Search v-model:model="searchParams" @reset="resetSearchParams" @search="getDataByPage"></Search>
    <!-- 登录规则列表 -->
    <ElCard class="sm:flex-1-hidden card-wrapper" body-class="ht50">
      <template #header>
        <div class="flex items-center justify-between">
          <p>{{ $t('page.manage.userLoginRule.title') }}</p>
          <TableHeaderOperation v-model:columns="columnChecks" :disabled-delete="checkedRowKeys.length === 0"
            :loading="loading" @add="handleAdd" @delete="handleBatchDeleted" @refresh="getData" />
        </div>
      </template>
      <div class="h-[calc(100%-50px)]">
        <ElTable v-loading="loading" height="100%" border class="sm:h-full" :data="data" row-key="id"
          @selection-change="checkedRowKeys = $event">
          <ElTableColumn v-for="col in columns" :key="col.prop" v-bind="col" />
        </ElTable>
      </div>
      <div class="mt-20px flex justify-end">
        <ElPagination v-if="mobilePagination.total" layout="total,prev,pager,next,sizes" v-bind="mobilePagination"
          v-model:current-page="mobilePagination.currentPage" v-model:page-size="mobilePagination.pageSize" />
      </div>

      <OperateModal v-model:visible="isVisible" :operate-type="operateType" :edit-id="editingId"
        @submitted="getDataByPage" />

    </ElCard>
  </div>
</template>

<style scoped></style>
